<script setup>
import { ref, reactive, onMounted, onBeforeUnmount, watch } from 'vue'
import {
  Avatar,
  View,
  UploadFilled,
  SuccessFilled,
  CircleCloseFilled
} from '@element-plus/icons-vue'
import {
  getAllBusinesses,
  getUserByName,
  getWork,
  getLastWork,
  saveWork,
  hasFinished
} from '@/api/api'
import { zcType, dateFormat, timeFormat, workTemplate } from '@/assets/const'
import { ElMessage } from 'element-plus'
import XxmpWork from '@/components/XxmpWork.vue'
import ZsgzWork from '@/components/ZsgzWork.vue'
import SjgjWork from '@/components/SjgjWork.vue'
import previewDialog from '@/components/previewDialog.vue'

const startDate = ref(localStorage.getItem('startDate') || '')
let userId = localStorage.getItem('userId')
const fisrtLogin = userId == null

const userDialogVisible = ref(fisrtLogin)
const name = ref(localStorage.getItem('userName'))
const date = ref(dateFormat())
const work = ref(workTemplate())
const businessOptions = ref([])
const formRef = ref(null)

// 预览
let previewDataDialogRef = ref(null)
const previewData = () => {
  previewDataDialogRef.value.open(work.value, name.value, startDate.value, getSelectedText())
}
const getSelectedText = () => {
  const res = businessOptions.value.filter((i) => i.id == work.value.businessId)
  if (res.length) {
    return res[0].name
  }
  return '暂无'
}

// 切换用户
const confirmName = async () => {
  if (name.value == localStorage.getItem('userName')) {
    userDialogVisible.value = false
    return
  }
  const res = await getUserByName({ params: { name: name.value } })
  if (res.status) return ElMessage.warning(res.msg)
  userId = res.data.id
  localStorage.setItem('userId', userId)
  localStorage.setItem('userName', name.value)
  localStorage.setItem('startDate', res.data.date)
  localStorage.setItem('businessId', res.data.businessId)
  localStorage.setItem('zcType', res.data.zcType)
  startDate.value = res.data.date
  getWorkForm()
  userDialogVisible.value = false
}

// 获取日报内容
const getWorkForm = async () => {
  const res = await getWork({ params: { userId, date: dateFormat(date.value) } })
  if (res.status) return ElMessage.warning('查询日报内容失败！')
  const data = { ...res.data }
  if (data.xxmp && data.xxmp.length == 0) delete data.xxmp
  if (data.sjgj && data.sjgj.length == 0) delete data.sjgj
  if (data.zsgz && data.zsgz.length == 0) delete data.zsgz
  work.value = Object.assign(workTemplate(), data)
}

// 上传
const uploadData = async () => {
  await formRef.value.validate(async (valid, fields) => {
    let { sjgj, zsgz, xxmp } = work.value
    sjgj = sjgj.filter((i) => i.projectName !== '' || i.content !== '')
    zsgz = zsgz.filter((i) => i.businessWorkType !== '' || i.content !== '')
    xxmp = xxmp.filter((i) => i.infoType !== '' || i.content !== '')
    const itemLength = sjgj.length + zsgz.length + xxmp.length

    if (itemLength < 1) return ElMessage.warning('请填写日报内容！')

    if (valid) {
      work.value = Object.assign(work.value, { sjgj, zsgz, xxmp })
      const params = {
        userId,
        date: dateFormat(date.value),
        ...JSON.parse(JSON.stringify(work.value))
      }
      const res = await saveWork(params)
      if (res.status) return ElMessage.warning('保存失败！')
      ElMessage.success('保存成功！')
      getWorkForm()
    }
  })
}

const hasFinished__ = async () => {
  if (!work.value.id) return ElMessage.warning('请先填写日报内容！')

  const res = await hasFinished({ id: work.value.id })
  if (res.status) return ElMessage.warning('保存失败！')
  ElMessage.success('今日日报已完成')
  work.value.finished = true
}

onMounted(async () => {
  // 获取日报内容
  if (!fisrtLogin) getWorkForm()
  // 获取单位列表
  const res = await getAllBusinesses()
  if (res.status) return ElMessage.warning('获取单位失败！')
  businessOptions.value = res.data
})

onBeforeUnmount(() => {
  uploadData()
})

watch(date, () => {
  getWorkForm()
})

const rules = reactive({
  zcType: [
    {
      required: true,
      message: '请选择驻场类型',
      trigger: 'change'
    }
  ],
  businessId: [
    {
      required: true,
      message: '请选择驻商单位',
      trigger: 'change'
    }
  ],
  date: [
    {
      type: 'date',
      required: true,
      message: '请选择日期',
      trigger: 'change'
    }
  ]
})

const importLast = async () => {
  const res = await getLastWork({ params: { userId, date: dateFormat(date.value) } })
  if (res.status) return ElMessage.warning('查询上条日报内容失败！')
  const data = { ...res.data }
  delete data.date
  delete data.finished
  delete data.lastTime
  delete data.id
  if (data.xxmp && data.xxmp.length == 0) delete data.xxmp
  if (data.sjgj && data.sjgj.length == 0) delete data.sjgj
  if (data.zsgz && data.zsgz.length == 0) delete data.zsgz
  work.value = Object.assign(work.value, data)
}
</script>
<template>
  <div>
    <header class="header">
      <div class="icon" @click="userDialogVisible = true">
        <el-icon size="20" color="white"> <Avatar /></el-icon>
      </div>
      <div class="one">{{ name }}{{ dateFormat(date) }}的日报</div>
      <div>最近保存{{ timeFormat(work.lastTime) }}</div>
    </header>
    <main>
      <div class="fixed-item">
        <div class="icon" @click="previewData">
          <el-icon size="20" color="white"> <View /></el-icon>
        </div>
        <br />
        <div class="icon" @click="uploadData">
          <el-icon size="20" color="white"> <UploadFilled /></el-icon>
        </div>
        <br />
        <div class="icon" @click="hasFinished__">
          <el-icon size="20" :color="work.finished ? 'lightgreen' : 'yellow'">
            <SuccessFilled v-if="work.finished" />
            <CircleCloseFilled v-else />
          </el-icon>
        </div>
      </div>
      <el-container>
        <el-header>
          基本信息
          <el-button type="primary" style="float: right; margin-top: 4px" @click="importLast()"
            >导入上一篇</el-button
          ></el-header
        >
        <el-main style="padding: 20px 20px 0 0">
          <el-form
            :model="work"
            :rules="rules"
            ref="formRef"
            label-width="120px"
            class="demo-ruleForm"
            status-icon
          >
            <el-form-item label="日报时间">
              <el-date-picker v-model="date" type="date" style="width: 100%" />
            </el-form-item>
            <el-form-item label="开始时间">
              <el-input :value="startDate" disabled />
            </el-form-item>
            <el-form-item label="驻商人员">
              <el-input v-model="name" disabled />
            </el-form-item>
            <el-form-item label="驻商单位" prop="businessId">
              <el-select v-model="work.businessId" filterable placeholder="驻商单位">
                <el-option
                  v-for="item in businessOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="地市公司">
              <el-input :value="`威海分公司`" disabled />
            </el-form-item>
            <el-form-item label="驻场类" prop="zcType">
              <el-radio-group v-model="work.zcType">
                <el-radio v-for="(item, key) in zcType" :key="key" :value="item" :label="item" />
              </el-radio-group>
            </el-form-item>
            <el-form-item label="工作内容">
              <el-input v-model="work.workContent" type="textarea" autosize />
            </el-form-item>
          </el-form>
        </el-main>
      </el-container>
      <el-container>
        <el-header>信息摸排</el-header>
        <el-main>
          <XxmpWork v-model="work.xxmp" />
        </el-main>
      </el-container>
      <el-container>
        <el-header>商机跟进</el-header>
        <el-main>
          <SjgjWork v-model="work.sjgj" />
        </el-main>
      </el-container>
      <el-container>
        <el-header>驻商工作</el-header>
        <el-main>
          <ZsgzWork v-model="work.zsgz" />
        </el-main>
      </el-container>
    </main>
    <el-dialog
      v-model="userDialogVisible"
      title="请输入您的姓名"
      style="max-width: 500px"
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form>
        <el-input v-model="name" />
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="confirmName()">确认</el-button>
        </span>
      </template>
    </el-dialog>
    <previewDialog ref="previewDataDialogRef"></previewDialog>
  </div>
</template>
<style lang="less">
header.header {
  text-align: center;
  background: #f593af;
  height: 65px;
  color: white;
  position: relative;
  padding-top: 5px;
  .one {
    font-size: 18px;
    font-weight: bold;
    line-height: 30px;
  }
  .icon {
    width: 30px;
    height: 30px;
    padding-top: 3px;
    border-radius: 100%;
    border: 1px solid white;
    float: right;
    top: 15px;
    right: 20px;
    position: absolute;
    cursor: pointer;
  }
}
.el-container {
  margin-bottom: 10px;
}

.fixed-item {
  position: fixed;
  z-index: 1;
  bottom: 60px;
  left: 20px;
  zoom: 1.4;
  .icon {
    width: 30px;
    height: 30px;
    padding-top: 5px;
    border-radius: 9%;
    cursor: pointer;
    text-align: center;
    background: #79bbff;
  }
}

.el-header {
  background: rgb(180, 238, 231);
  line-height: 40px;
  height: 40px;
  font-size: 16px;
}

.el-main {
  border: 1px solid rgb(180, 238, 231);
  border-radius: 0 0 10px 10px;
}
</style>
